package com.wyix.service;

import com.wyix.domain.Book;
import com.wyix.domain.BorrowRecord;
import com.wyix.domain.User;
import com.wyix.repository.BorrowRecordRepository;
import com.wyix.repository.UserRepository;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author wangdx
 * @since 2025/8/26
 */
@Service
@RequiredArgsConstructor
public class BorrowService {
    private final Logger logger = LoggerFactory.getLogger(BorrowService.class);
    private final BorrowRecordRepository borrowRecordRepository;
    private final UserRepository userRepository;
    private final BookService bookService;

    /**
     * 借阅图书（事务：确保用户存在、图书存在、库存足够、记录保存）
     */
    @Transactional
    public BorrowRecord borrowBook(Long userId, Long bookId) {
        // 1. 校验用户和图书是否存在
        User user = userRepository.findById(userId).orElseThrow(() -> new RuntimeException("用户不存在：ID=" + userId));
        Book book = bookService.getBookById(bookId);

        // 2. 校验用户是否已借阅该未归还的图书
        List<BorrowRecord> unreturnedRecords = borrowRecordRepository.findUnreturnedRecordsByUserId(userId);
        boolean hasUnreturned = unreturnedRecords.stream()
                .anyMatch(record -> record.getBook().getId().equals(bookId));
        if (hasUnreturned) {
            throw new RuntimeException("用户已借阅该图书，未归还：书名=" + book.getBookName());
        }

        // 3. 减少图书库存
        bookService.decreaseStock(bookId, 1);

        // 4. 创建借阅记录
        BorrowRecord record = new BorrowRecord();
        record.setUser(user);
        record.setBook(book);
        record.setBorrowTime(new Date());
        record.setStatus(0);  // 0-未归还

        logger.info("用户借阅图书：用户名={}，书名={}，借阅时间={}", user.getUsername(), book.getBookName(), record.getBorrowTime());
        return borrowRecordRepository.save(record);
    }

    /**
     * 归还图书（事务：更新借阅记录、增加库存）
     */
    @Transactional
    public BorrowRecord returnBook(Long borrowRecordId) {
        // 1. 查找借阅记录
        BorrowRecord record = borrowRecordRepository.findById(borrowRecordId)
                .orElseThrow(() -> new RuntimeException("借阅记录不存在：ID=" + borrowRecordId));

        // 2. 校验是否已归还
        if (record.getStatus() == 1) {
            throw new RuntimeException("该图书已归还，无需重复操作：记录ID=" + borrowRecordId);
        }

        // 3. 更新借阅记录
        record.setReturnTime(new Date());
        record.setStatus(1);  // 1-已归还

        // 4. 增加图书库存
        Book book = record.getBook();
        book.setStock(book.getStock() + 1);

        logger.info("用户归还图书：用户名={}，书名={}，归还时间={}",
                record.getUser().getUsername(), book.getBookName(), record.getReturnTime());
        return borrowRecordRepository.save(record);
    }

    /**
     * 查询用户的借阅记录
     */
    public List<BorrowRecord> getUserBorrowRecords(Long userId) {
        logger.info("查询用户借阅记录：用户ID={}", userId);
        return borrowRecordRepository.findByUserId(userId);
    }
}
